import { defineStore } from 'pinia'
import { ordersApi, type OrderListItem } from '@/api/orders'

interface OrderState {
  orders: OrderListItem[]
  loading: boolean
  error: string | null
}

export const useOrderStore = defineStore('order', {
  state: (): OrderState => ({
    orders: [],
    loading: false,
    error: null,
  }),

  getters: {
    // 根据数字状态过滤
    filteredOrders: (state) => (status?: number) => {
      if (status === undefined || status === null) return state.orders
      return state.orders.filter((order) => order.order_status === status)
    },

    // 根据文本状态过滤
    filteredOrdersByText: (state) => (statusText?: string) => {
      if (!statusText) return state.orders
      return state.orders.filter((order) => order.order_status_text === statusText)
    },

    // 智能过滤：支持数字和文本状态
    smartFilteredOrders: (state) => (filter?: number | string) => {
      if (filter === undefined || filter === null || filter === '') return state.orders

      if (typeof filter === 'number') {
        return state.orders.filter((order) => order.order_status === filter)
      }

      if (typeof filter === 'string') {
        return state.orders.filter((order) => order.order_status_text === filter)
      }

      return state.orders
    },
  },

  actions: {
    async fetchOrders() {
      this.loading = true
      this.error = null

      try {
        const response = await ordersApi.getOrderList()
        this.orders = response.results
      } catch (err) {
        this.error = err instanceof Error ? err.message : '获取订单失败'
      } finally {
        this.loading = false
      }
    },
  },
})
